<template>
  <view class="cashier">
    <view class="price">¥{{ orderInfo.paid_amount }}</view>
    <view class="orderNo">订单号：{{ orderInfo.order_id }}</view>
    <u-count-down
      :time="orderInfo.surplusTime"
      format="DD:HH:mm:ss"
      auto-start
      millisecond
      @change="onChange"
    >
      <view class="time">
        支付剩余时间：
        <text class="time__item">{{ timeData.days }}天</text>
        <text class="time__item">{{ timeData.hours>10?timeData.hours:'0'+timeData.hours }}时</text>
        <text class="time__item">{{ timeData.minutes }}分</text>
      </view>
    </u-count-down>
    <view class="payType">
      <!--#ifdef MP-ALIPAY-->
      <view class="info-img"><text class="icon-ali font_family icon-Alipay_tongyong_1" />支付宝支付</view>
      <view class="radioDefault radioAcitve">
        <u-icon name="checkmark" color="#FFFFFF" size="10" />
      </view>
      <!--#endif-->
      <!--#ifdef MP-WEIXIN-->
      <view class="info-img"><text class="icon-wx font_family icon-a-WeChatpay_tongyong_1" />微信支付</view>
      <view class="radioDefault radioAcitve">
        <u-icon name="checkmark" color="#FFFFFF" size="10" />
      </view>
      <!--#endif-->
      <!--#ifdef H5 -->
      <view v-if="isWeixin" class="info-img"><text class="icon-wx font_family icon-a-WeChatpay_tongyong_1" />微信支付</view>
      <view v-if="isAlipay" class="info-img"><text class="icon-ali font_family icon-Alipay_tongyong_1" />支付宝支付</view>
      <view v-if="isWeixin || isAlipay" class="radioDefault radioAcitve">
        <u-icon name="checkmark" color="#FFFFFF" size="10" />
      </view>
      <view v-if="isOther">
        <view class="otherweb" @click="checkWeixin()">
          <view class="info-img"><text class="icon-wx font_family icon-a-WeChatpay_tongyong_1" />微信支付</view>
          <view v-if="showWX" class="radioDefault radioAcitve otherwebRiter">
            <u-icon name="checkmark" color="#FFFFFF" size="10" />
          </view>
          <view v-if="showAL" class="radioDefault NOradioAcitve otherwebRiter">
            <u-icon name="checkmark" color="#FFFFFF" size="10" />
          </view>
        </view>
        <view class="otherweb" @click="checkAli()">
          <view class="info-img"><text class="icon-ali font_family icon-Alipay_tongyong_1" />支付宝支付</view>
          <view v-if="showAL" class="radioDefault radioAcitve otherwebRiter">
            <u-icon name="checkmark" color="#FFFFFF" size="10" />
          </view>
          <view v-if="showWX" class="radioDefault NOradioAcitve otherwebRiter">
            <u-icon name="checkmark" color="#FFFFFF" size="10" />
          </view>
        </view>

      </view>

    <!--#endif-->
    </view>

    <view class="tips">温馨提示：</view>
    <!--#ifdef MP-ALIPAY-->
    <view class="tips" style="margin-top: 8rpx;">为了您顺利完成支付，请查看支付宝支付的单次限制！</view>
    <!--#endif-->
    <!--#ifdef MP-WEIXIN-->
    <view class="tips" style="margin-top: 8rpx;">为了您顺利完成支付，请查看微信支付的单次限制！</view>
    <!--#endif-->
    <!--#ifdef H5 -->
    <view v-if="isWeixin" class="tips" style="margin-top: 8rpx;">为了您顺利完成支付，请查看微信支付的单次限制！</view>
    <view v-if="isAlipay" class="tips" style="margin-top: 8rpx;">为了您顺利完成支付，请查看支付宝支付的单次限制！</view>
    <view v-if="isOther" class="tips" style="margin-top: 8rpx;">为了您顺利完成支付，请查看微信或支付宝支付的单次限制！</view>
    <!--#endif-->

    <view class="footer">
      <!--#ifdef MP-ALIPAY || MP-WEIXIN-->
      <view class="button" @click="$u.throttle(confrimTrans, 500)">立即支付</view>
      <!--#endif-->
      <!--#ifdef H5-->
      <view class="button" @click="$u.throttle(MconfrimTrans, 500)">立即支付</view>
      <!--#endif-->
    </view>
  </view>
</template>

<script>
import { savePayInfo, combinePay, McombinePay, getMpPayurlLink, createPaySerialno } from '@/api/orderApi';
import { tokenByCodeForAli } from '@/api/login';
import { getAuthCode } from '@/utils/login';
import {
  prePayMethod,
  payMethod
} from '@/payments/payMethod'
export default {
  data() {
    return {
      timeData: {},
      orderInfo: {},
      payInfo: {},
      prePayInfo: {}, // prePay预支付接口返回参数信息
      userId: '',
      isWeixin: false,
      isAlipay: false,
      isOther: false,
      showWX: true,
      showAL: false
    }
  },
  onLoad(option) {
    //#ifdef H5
    if (/MicroMessenger/.test(window.navigator.userAgent)) {
      this.isWeixin = true
    } else if (/AlipayClient/.test(window.navigator.userAgent)) {
      this.isAlipay = true
    } else {
      this.isOther = true
    }
    //#endif
    this.orderInfo = JSON.parse(option.params)
    const { surplusTime = '' } = JSON.parse(option.params)
    if (!surplusTime) this.orderInfo.surplusTime = 5 * 24 * 60 * 60 * 1000
    this.paymentFn()
    this.getUserId()
  },
  methods: {
    prePayMethod,
    payMethod,
    async getUserId() {
      console.log('8888888888', this.vuex_login_code, this.vuex_accountInfo)
      // #ifdef MP-WEIXIN
      const provider = this.vuex_provider;
      getAuthCode(provider, (loginRes) => {
        if (loginRes.code) {
          this.code = loginRes.code
        }
      })
      // #endif
      // #ifdef MP-ALIPAY
      const params = {
        code: this.vuex_login_code,
        branchId: null, //销售公司id
        branchName: null, //销售公司名称
      }
      if (this.vuex_accountInfo.userId) {
        this.userId = this.vuex_accountInfo.userId
      } else {
        const res = await tokenByCodeForAli(params)
        if (res.errorCode == 0) {
          var vuex_accountInfo = { ...this.vuex_accountInfo }
          vuex_accountInfo.userId = res.data.userId
          this.$u.vuex('vuex_accountInfo', vuex_accountInfo)
          this.userId = res.data.userId
        }
      }
      // #endif
    },
    onChange(e) {
      this.timeData = e
    },
    async paymentFn() {
      const { order_id, paid_amount } = this.orderInfo
      //#ifdef H5
      const payWayCode = 1006
      const params = {
        'orderIds': order_id,
        'totalAmount': paid_amount,
        'payType': 10, // 10-下单；20-结算
        'payWayCode': payWayCode,
        'accountFlag': 0
      }
      savePayInfo(params).then((res) => {
        if (res.errorCode == 0) {
          this.payInfo = res.data
        } else {
          this.$u.toast(res.msg);
        }
      })
      // #endif
      // #ifdef MP-ALIPAY || MP-WEIXIN
      const prePayParams = { platform: 'YC', orderId: order_id, totalAmount: paid_amount }
      console.log('这是支付获取支付信息', prePayParams)
      this.prePayInfo = await this.prePayMethod(prePayParams).catch((e) => {
        this.$u.toast(e.message)
      })

      console.log('预支付的数据', this.prePayInfo)
      // #endif
    },
    async confrimTrans() {
      // let payWayName = 'YeeWechatPay'
      // // #ifdef MP-ALIPAY
      // payWayName = 'YeeAliPay'
      // // #endif
      // const params = {
      //   params: [
      //     {
      //       payId: this.payInfo.payId,
      //       payWayName,
      //       platform: 20,
      //       wxCode: this.code,
      //       // #ifdef MP-ALIPAY
      //       userId: this.userId,
      //       // #endif
      //       accountPwd: '',
      //       ipAddress: '1.1.1.1',
      //       payableAmount: this.payInfo.needPayAmount,
      //       applet: true
      //     }
      //   ]
      // }
      // const res = await combinePay(params)
      // if (res.errorCode == 0) {
      //   // #ifdef MP-ALIPAY
      //   this.requestPaymentFn(res.data.prePayTn)
      //   // #endif
      //   // #ifdef MP-WEIXIN
      //   this.requestPaymentFn(res.data.prePayTn)
      //   // #endif
      // } else {
      //   uni.$u.toast(res.msg)
      // }

      let payWayUnifyCode = 'WechatPay' // 支付方式统一编码，用于不区分支付渠道，由服务端根据规则选择支付渠道 WechatPay=微信支付 AliPay=支付宝 EPay=网银支付 QuickPay=快捷 AccountPay=账期 PingAnPay=平安支付
      // #ifdef MP-ALIPAY
      payWayUnifyCode = 'AliPay'
      // #endif
      console.log('预支付的数据', this.prePayInfo)
      const {
        needPayAmount,
        payId,
        totalAmount,
      } = this.prePayInfo
      const { order_id, paid_amount } = this.orderInfo
      const payParams = {
        platform: 'YC',
        payWayUnifyCode,
        payId,
        payableAmount: needPayAmount,
        payInfoTotalAmount: totalAmount
      }
      console.log('支付入参', payParams)
      // 支付成功回调函数
      const successFn = ({ paySerialnoId }) => {
        uni.redirectTo({
          url: `/payments/paySuccess/index?id=${paySerialnoId}&amount=${paid_amount}&order_id=${order_id}&type=pay`
        });
        this.$u.vuex('vuex_qrOrderNo', '')
      }
      // 支付失败回调函数
      const failFn = () => {
        this.$u.toast('支付失败')
      }
      await this.payMethod(payParams, successFn, failFn)
    },
    /* m站点击支付*/
    MconfrimTrans() {
      //#ifdef H5
      if (this.isAlipay) {
        this.MrequestPaymentFn()
      } else if (this.isWeixin) {
        this.createPaySerialnoFn()
      } else {
        if (this.showWX) {
          this.createPaySerialnoFn()
        } else {
          this.MrequestPaymentFn()
        }
      }
      // #endif
    },
    /*m站调支付宝支付*/
    MrequestPaymentFn() {
      const { payId, needPayAmount } = this.payInfo
      const paramsdata = [{
        payId: payId,
        platform: 20,
        payWayName: 'YeeAliPay',
        payableAmount: needPayAmount
      }]
      McombinePay({ 'params': paramsdata }).then(res => {
        if (res.errorCode == 0) {
          window.location.href = res.data.prePayTn
        } else {
          uni.$u.toast(res.msg)
          setTimeout(function(){
          uni.redirectTo({
            url: '/pages/order/moreOrder'
          });
          },3000)

        }
      }).catch((res) => {
        this.$u.toast(res.msg)
      })
    },
    createPaySerialnoFn() {
      const { payId, needPayAmount } = this.payInfo
      const paramsdata = [{
        payId: payId,
        platform: 20,
        payWayName: 'YeeWechatPay',
        payableAmount: needPayAmount
      }]
      createPaySerialno({ 'params': paramsdata }).then(res => {
        if (res.errorCode == 0) {
          this.getMpPayurlLinkFn(res.data.paySerialnoId)
        } else {
          uni.$u.toast(res.msg)
        }
      }).catch((res) => {
        this.$u.toast(res.msg)
      })
    },
    getMpPayurlLinkFn(paySerialnoId) {
      const params = {
        paySerialnoId: paySerialnoId
      }
      getMpPayurlLink(params).then(res => {
        if (res.code == 0) {
          window.location.href = res.data.url_link
        } else {
          uni.$u.toast(res.msg)
          window.location.reload()
        }
      }).catch((res) => {
        this.$u.toast(res.msg)
      })
    },
    /*调起支付*/
    requestPaymentFn(prePayTn) {
      const provider = this.vuex_provider;
      const { order_id, paid_amount, platform } = this.orderInfo
      const { timeStamp = '', nonceStr = '', signType = '', paySign = '' } = prePayTn
      uni.requestPayment({
        'provider': provider,
        'orderInfo': prePayTn, //支付宝小程序参数
        'timeStamp': timeStamp, //wx 时间戳
        'nonceStr': nonceStr, //wx 随机字符串
        'package': prePayTn.package, //wx 订单详情扩展字符串
        'signType': signType, //wx 签名方式，默认RSA
        'paySign': paySign, //wx 支付签名
        success: (res) => {
          // 支付宝支付成功跳转页面
          // #ifdef MP-ALIPAY
          if (res.resultCode == 9000) { //不加此判断，支付宝取消支付时就会跳到支付成功
            uni.redirectTo({
              url: '/payments/paySuccess/index?id=' + this.payInfo.payId + '&amount=' + paid_amount + '&order_id=' + order_id + '&type=pay'
            });
            uni.$u.vuex('vuex_qrOrderNo', '')
          }
          // #endif
          /*微信支付成功*/
          // #ifdef MP-WEIXIN
          uni.redirectTo({
            url: '/payments/paySuccess/index?id=' + this.payInfo.payId + '&amount=' + paid_amount + '&order_id=' + order_id + '&type=pay'
          });
          uni.$u.vuex('vuex_qrOrderNo', '')
          // #endif
        },
        fail: (error) => {
          if (platform == 10 || !!platform == 20 || !platform) {
            uni.navigateTo({
              url: `/orders/moreOrderDetail/index?id=${order_id}`
            })
          } else {
            uni.navigateTo({
              url: '/orders/order-details/order-details?orderNo=' + order_id
            })
          }
          console.log(error, '执行')
          // 失败取消订单锁定
          // lockOrderFn(orderNo, 0)
        }
      })
    },
    //#ifdef H5
    checkWeixin() {
      this.showWX = true
      this.showAL = false
    },
    checkAli() {
      this.showAL = true
      this.showWX = false
    }
    // #endif
  }
}
</script>
<style lang="scss" scoped>
  page {
    background:$uni-bg-color;
  }
.cashier {
  padding: 26rpx 32rpx;
  box-sizing: border-box;
  .footer {
    display: flex;
    position: fixed;
    bottom: 90rpx;
    left: 0;
    justify-content: space-between;
    align-items: center;
    align-content: center;
    width: 100%;
    padding: 0rpx 32rpx;
    box-sizing: border-box;
    .button {
      width: 624rpx;
      height: 64rpx;
      background: linear-gradient(128.8deg, rgba(255,121,95,1) 0%, rgba(238,61,26,1) 100%);
      margin: 0 auto;
      display: flex;
      justify-content: center;
      align-content: center;
      align-items: center;
      border-radius: $uni-border-radius-default;
      font-size:$uni-font-size-base;
      color:$uni-text-color-inverse;
    }
  }
  .tips {
    color: $uni-text-color-grey;
    font-size:$uni-font-size-sm;
  }
  .payType {
    border-top: 2rpx solid $uni-border-gray;
    display: flex;
    justify-content: space-between;
    align-items: center;
    align-content: center;
    margin: 32rpx 0rpx;
    padding-top: 20rpx;
    .info-img {
      display: flex;
      align-items: center;
      width: 654rpx;
      .icon-wx{
        color: #09bb07;
        font-size: 48rpx;
        margin-right: 16rpx;
      }
      .icon-ali{
        color: #2785ff;
        font-size: 48rpx;
        margin-right: 16rpx;
      }
    }
    .radioDefault {
      flex-shrink: 0;
      width: 32rpx;
      height: 32rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      align-content: center;
      border: 1rpx solid #D3D3D3;
      margin-right: 16rpx;
      border-radius:$uni-border-radius-circle;
    }
    .radioAcitve {
      background:$uni-bg-color-orange;
      border:2rpx solid #FF5533;
    }
    .NOradioAcitve {
      background: $uni-bg-color;
      border:2rpx solid #FF5533;
    }
    .otherweb {
      display: flex;
      height: 102rpx;
      line-height: 102rpx;
      border-bottom:1rpx solid $uni-border-gray;
      align-items: center;
      .otherwebRiter {
        float: right;
      }
    }
  }
  .price {
    color:$uni-text-color-orange;
    font-size: 64rpx;
    font-weight:bold;
    text-align: center;
  }
  .orderNo {
    margin: 8rpx 0;
    text-align: center;
    color:$uni-text-color;
    font-size:$uni-font-size-sm;
  }
  .time {
    text-align: center;
    color:$uni-text-color-orange;
    font-size:$uni-font-size-sm;
  }
}
</style>
